var Passport = require('passport'),
    FacebookTokenStrategy = require('passport-facebook-token'),

    apiHandler = require('../services/api-handler'),
    jWT = require('../helpers/jwt'),
    logger = require('../models/logger'),
    facebook = require('../config/secrets').facebook,
    authToken = require('../models/auth-token'),
    users = require('../models/user');

Passport.use(new FacebookTokenStrategy({
        clientID: facebook.clientID,
        clientSecret: facebook.clientSecret,
        profileFields: facebook.profileFields
    }, function (accessToken, refreshToken, profile, done) {
        var email = profile && profile._json && profile._json.email;
        if (email) {
            users.getUserByEmail(String(email), function (err, user) {
                if (err) {
                    var errorLog = new logger({
                        details: err,
                        activity: 'User account confirmation'
                    });
                    errorLog.save();
                    return done(null, false, {message: 'INVALID_USER'});
                } else if (!err && !user) {
                    var newUser = new users({
                        firstName: profile._json.first_name,
                        lastName: profile._json.last_name,
                        email: profile._json.email,
                        password: '123'
                    });
                    users.createUser(newUser, function (err, user) {
                        var errorLog = new logger({
                            details: err,
                            activity: 'User account confirmation'
                        });
                        errorLog.save();
                        return done(null, user);
                    });

                } else if (!err && user) {
                    return done(null, user);
                }
            });
        } else {
            return done(null, false, {message: 'FB_PROFILE_WITHOUT_EMAIL'});
        }
    }
));

exports.facebook = function (req, res, next) {
    Passport.authenticate('facebook-token', {scope: ['email']}, function (err, user, info) {
        var token, newToken;
        if (!err && !user && info) {
            apiHandler.setErrorResponse(info.message, res);
        } else if (user) {
            token = jWT.getLoginToken(user);
            newToken = new authToken({
                user: user,
                token: token
            });
            authToken.createToken(newToken, function (err, authUser) {
                if (err) {
                    req.user = null;
                    apiHandler.setErrorResponse('LOGIN_FAILED', res);
                } else {
                    var data = {token: token, user: user};
                    apiHandler.setSuccessResponse(data, res);
                }
            });
        } else {
            apiHandler.setErrorResponse('LOGIN_FAILED', res);
        }
    })(req, res, next);
};
